package com.koron.tool.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.DefaultIdGenerator;
import com.koron.tool.bean.ToolBean;
import com.koron.tool.bean.ToolGroupBean;
import com.koron.tool.bean.ToolQuery;
import com.koron.tool.bean.ToolSelect;
import com.koron.tool.enums.ToolGroupHierarchy;
import com.koron.tool.mapper.TooSelectMapper;
import com.koron.tool.mapper.ToolAccountsManagerMapper;
import com.koron.tool.service.ToolAccountsManagerService;
import com.koron.tool.util.BeanUtil;
import com.koron.tool.util.Randt;
import com.koron.tool.util.ToolConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ToolAccountsManagerServiceImpl implements ToolAccountsManagerService {
    /**
     * 添加工器具树结构
     *
     * @param factory
     * @param bean    实例对象
     * @return
     */
    @Override
    @TaskAnnotation("addGroup")
    public Response addGroup(SessionFactory factory, EamUser user, ToolGroupBean bean) {
        try {
            if (StringUtils.isEmpty(bean.getName())) {
                return Response.fail("名称不能为空");
            }
            if (bean.getName().contains(".")) {
                return Response.fail("名称不能有“.”");
            }
            if (StringUtils.isEmpty(bean.getParent())) {
                return Response.fail("父节点不能为空");
            }
            if (StringUtils.isEmpty(bean.getHierarchy())) {
                return Response.fail("所属层级不能为空");
            }
            Response response = checkHierarchy(factory, bean);
            if (response.getCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return response;
            }

            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            // 生成纯数字编码
            String code = DefaultIdGenerator.getInstance().generateLongId();
            //自动生成组织编码
            bean.setCode(code);

            if (StringUtils.isEmpty(bean.getParent())) {
                Integer root = mapper.getParent("root");
                if (root > 0) {
                    return Response.fail("已存在父节点，父节点不能为空");
                }
                // 初始父节点
                bean.setParent("root");
            }
            BeanUtil.add(user, bean);
            bean.setLevel(Integer.parseInt(bean.getHierarchy()));
            Integer value = mapper.insertGroup(bean);
            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("保存失败");
        }
    }


    public Response checkHierarchy(SessionFactory factory, ToolGroupBean bean) {
        Response response = Response.ok();
        if (StringUtils.isEmpty(bean.getName())) {
            return Response.fail("名称不能为空");
        }
        if (bean.getName().contains(".")) {
            return Response.fail("名称不能有“.”");
        }
        if (StringUtils.isEmpty(bean.getParent())) {
            return Response.fail("父节点不能为空");
        }
        if (StringUtils.isEmpty(bean.getHierarchy())) {
            return Response.fail("所属层级不能为空");
        }

        ToolAccountsManagerMapper toolAccountsManagerMapper = factory.getMapper(ToolAccountsManagerMapper.class);
        ToolGroupBean parentNode = toolAccountsManagerMapper.getGroup(bean.getParent());
        if (Objects.isNull(parentNode)) {
            return Response.fail("父节点不存在！");
        }
        Integer parentNodeLevel = parentNode.getLevel();
        int level = Integer.parseInt(bean.getHierarchy());
        if (!((parentNodeLevel == ToolGroupHierarchy.COMPANY.getLevel() &&
                (level == ToolGroupHierarchy.COMPANY.getLevel() || level == ToolGroupHierarchy.STATION.getLevel() ||
                        level == ToolGroupHierarchy.WAREHOUSE.getLevel()))
                ||
            (parentNodeLevel == ToolGroupHierarchy.STATION.getLevel() && level == ToolGroupHierarchy.WAREHOUSE.getLevel())
            ||
            (parentNodeLevel == ToolGroupHierarchy.WAREHOUSE.getLevel() && level == ToolGroupHierarchy.GOODS_SHELF.getLevel())
            ||
            (parentNodeLevel == ToolGroupHierarchy.GOODS_SHELF.getLevel()))
        ) {
            return Response.fail("该父节点下不能创建此层级！");
        }

        return response;
    }

    @Override
    @TaskAnnotation("getGroupOrder")
    public Response getGroupOrder(SessionFactory factory, EamUser user, String parent) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            Integer maxGroupOrder = mapper.getMaxGroupOrder(parent);
            maxGroupOrder += 1;
            return Response.ok(maxGroupOrder);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail();
        }

    }

    @Override
    @TaskAnnotation("getGroup")
    public Response getGroup(SessionFactory factory, String id) {
        if (StringUtils.isEmpty(id)) {
            return Response.fail("参数id不能为空");
        }
        ToolGroupBean group = factory.getMapper(ToolAccountsManagerMapper.class).getGroup(id);
        return Response.ok(group);
    }

    @Override
    @TaskAnnotation("updateGroup")
    public Response updateGroup(SessionFactory factory, EamUser user, ToolGroupBean bean) {
        try {
            if (StringUtils.isEmpty(bean.getId())) {
                return Response.fail("参数id不能为空");
            }
            if (StringUtils.isEmpty(bean.getName())) {
                return Response.fail("名称不能为空");
            }
            if (bean.getName().contains(".")) {
                return Response.fail("名称不能有“.”");
            }
            if (StringUtils.isEmpty(bean.getHierarchy())) {
                return Response.fail("所属层级不能为空");
            }
            if (StringUtils.isEmpty(bean.getParent())) {
                return Response.fail("父级节点不能为空");
            }

            Response response = checkHierarchy(factory, bean);



            if (response.getCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return response;
            }

            ToolAccountsManagerMapper toolAccountsManagerMapper = factory.getMapper(ToolAccountsManagerMapper.class);
            List<ToolGroupBean> list = toolAccountsManagerMapper.getChildList(bean.getId());
            List<ToolGroupBean> goodsShelfList = list.stream()
                    .filter(toolGroupBean -> toolGroupBean.getLevel() == ToolGroupHierarchy.GOODS_SHELF.getLevel())
                    .collect(Collectors.toList());
            if (bean.getLevel() != ToolGroupHierarchy.WAREHOUSE.getLevel() && CollectionUtils.isNotEmpty(goodsShelfList)) {
                return Response.fail("当前节点下存在货架，层级只能为仓库");
            }
            List<ToolGroupBean> warehouseList = list.stream()
                    .filter(toolGroupBean -> toolGroupBean.getLevel() == ToolGroupHierarchy.WAREHOUSE.getLevel())
                    .collect(Collectors.toList());
            if (!(bean.getLevel() == ToolGroupHierarchy.COMPANY.getLevel() ||
                    bean.getLevel() == ToolGroupHierarchy.STATION.getLevel())
                    &&
                    CollectionUtils.isNotEmpty(warehouseList)) {
                return Response.fail("当前节点下存在仓库，层级只能为公司或场站");
            }
            List<ToolGroupBean> stationList = list.stream()
                    .filter(toolGroupBean -> toolGroupBean.getLevel() == ToolGroupHierarchy.STATION.getLevel())
                    .collect(Collectors.toList());
            if (bean.getLevel() != ToolGroupHierarchy.COMPANY.getLevel() && CollectionUtils.isNotEmpty(stationList)) {
                return Response.fail("当前节点下存在场站，层级只能为公司");
            }
            List<ToolGroupBean> companyList = list.stream()
                    .filter(toolGroupBean -> toolGroupBean.getLevel() == ToolGroupHierarchy.COMPANY.getLevel())
                    .collect(Collectors.toList());
            if (bean.getLevel() != ToolGroupHierarchy.COMPANY.getLevel() && CollectionUtils.isNotEmpty(companyList)) {
                return Response.fail("当前节点下存在公司，层级只能为公司");
            }


/*
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            Integer nameExist = mapper.checkNameExist(bean);
            if (nameExist > 0) {
                return Response.fail("您修改的名称已存在");
            }
*/
            //Integer codeExist = mapper.checkCodeExistWithId(bean);
            //if (codeExist > 0) {
            //return Response.fail("您修改的编号已存在");
            //}
            BeanUtil.update(user, bean);
            bean.setLevel(Integer.parseInt(bean.getHierarchy()));
            Integer updateGroup = toolAccountsManagerMapper.updateGroup(bean);

            // 更新工器具信息
            ToolGroupBean parentNode = toolAccountsManagerMapper.getGroup(bean.getParent());
            if (Objects.isNull(parentNode)) {
                return Response.fail("父节点不存在！");
            }

            int level = bean.getLevel();
            if (level == ToolGroupHierarchy.GOODS_SHELF.getLevel()) {
                String goodsShelfCode = bean.getCode();
                String warehouseId = parentNode.getId();
                ToolGroupBean group = toolAccountsManagerMapper.getGroup(parentNode.getParent());
                String belongUnitId = group.getId();
                toolAccountsManagerMapper.updateToolByGoodsShelfCode(goodsShelfCode, warehouseId, belongUnitId);

            } else if (level == ToolGroupHierarchy.WAREHOUSE.getLevel()) {
                String warehouseId = bean.getId();
                String belongUnitId = parentNode.getId();
                toolAccountsManagerMapper.updateToolByWarehouseId(warehouseId, belongUnitId);

            }
            return Response.ok(updateGroup);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("修改失败");
        }
    }

    @Override
    @TaskAnnotation("deleteGroup")
    public Response deleteGroup(SessionFactory factory, String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            ToolGroupBean group = mapper.getGroup(id);
            if (null == group) {
                return Response.fail("数据不存在");
            }
            Integer checkChild = mapper.checkChild(id);
            if (checkChild > 0) {
                return Response.fail("存在子集，无法删除");
            }
            Integer checkTool = mapper.checkTool(id);
            if (checkTool > 0) {
                return Response.fail("存在数据，无法删除");
            }
            Integer delete = mapper.deleteGroup(id);
            return Response.ok("删除成功", delete);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("删除失败");
        }
    }

    @Override
    @TaskAnnotation("scrapTool")
    public Response scrapTool(SessionFactory factory, EamUser user, String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            // 先检验该工具是否已提交报废单
            Integer toolScrapStatus = mapper.getToolScrapStatus(id);
            if (toolScrapStatus > 0) {
                return Response.fail("该工具已提交报废单");
            }
            ToolBean tool = mapper.getTool(id);
            if (!ToolConstant.AVAILABLE_STATUS_AVAILABLE.equals(tool.getAvailableStatus())) {
                return Response.fail("该工具当前非可用状态，不能手动报废");
            }
            Integer value = mapper.scrapTool(id);
            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("手动报废失败");
        }
    }

    @Override
    @TaskAnnotation("addTool")
    public Response addTool(SessionFactory factory, EamUser user, ToolBean bean) {
        try {
            Response response = checkToolEmpty(bean);
            if (response.getCode() != Response.success().getCode()) {
                return response;
            }
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            BeanUtil.add(user, bean);
            // 生成纯数字编码
            //String code = DefaultIdGenerator.getInstance().generateLongId();
            Randt randt = new Randt();
            String code = randt.getRandt();
            bean.setRFID(code);
            bean.setCode(code);
//            bean.setCode(randt.getRandt());
            Integer value = mapper.insertTool(bean);
            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("保存失败");
        }
    }

    @Override
    @TaskAnnotation("getToolOrder")
    public Response getToolOrder(SessionFactory factory, EamUser user) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            Integer maxToolOrder = mapper.getMaxToolOrder();
            maxToolOrder += 1;
            return Response.ok(maxToolOrder);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail();
        }
    }


    @Override
    @TaskAnnotation("updateTool")
    public Response updateTool(SessionFactory factory, EamUser user, ToolBean bean) {
        try {
            if (StringUtils.isEmpty(bean.getId())) {
                return Response.fail("参数id不能为空");
            }
            Response response = checkToolEmpty(bean);
            if (response.getCode() != Response.success().getCode()) {
                return response;
            }
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
/*
            Integer inventoryPreparation = mapper.getInventoryPreparation(bean.getWarehouseId());
            String inventoryStatus = mapper.getInventoryStatus(bean.getId());
            if (inventoryPreparation == ToolConstant.INVENTORY_PREPARATION_YES &&
                    ! bean.getInventoryStatus().equals(inventoryStatus)) {
                return Response.fail("当前工器具所在库房处于盘点准备状态，禁止借出和归还工器具");
            }
*/
            BeanUtil.update(user, bean);
            Integer updateTool = mapper.updateTool(bean);
            return Response.ok(updateTool);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("修改失败");
        }
    }

    @Override
    @TaskAnnotation("getTool")
    public Response getTool(SessionFactory factory, EamUser user, String id) {
        if (StringUtils.isEmpty(id)) {
            return Response.fail("参数id不能为空");
        }
        ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
        ToolBean tool = mapper.getTool(id);
        return Response.ok(tool);
    }

    @Override
    @TaskAnnotation("deleteTool")
    public Response deleteTool(SessionFactory factory, EamUser user, String ids) {
        try {
            if (StringUtils.isEmpty(ids)) {
                return Response.fail("参数id不能为空");
            }
//            List<String> idList = JSONObject.parseArray(ids, String.class);
            List<String> idList = Arrays.asList(ids.split("[,，]"));
            Map map = new HashMap();
            map.put("idList",idList);
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
//            ToolBean tool = mapper.getTool(id);
//            if (null == tool) {
//                return Response.fail("数据不存在");
//            }
//            Integer delete = mapper.deleteTool(id);
            Integer delete = mapper.deleteToolBatch(map);
            return Response.ok("删除成功", delete);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("删除失败");
        }
    }


    @Override
    @TaskAnnotation("getList")
    public Response getList(SessionFactory factory, ToolQuery query) {
        Map map = new HashMap();
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            if (StringUtils.isEmpty(query.getId())) {
                List<ToolGroupBean> child = mapper.getChildList("root");
                if (null != child && child.size() > 0) {
                    map.put("bean", child.get(0));
                }

                map.put("group", new PageInfo(child));
                map.put("tool", new PageInfo<>());
                return Response.ok(map);
            }
            ToolGroupBean group = mapper.getGroup(query.getId());
            if (group == null) {
                map.put("bean", group);
                map.put("group", new PageInfo(new ArrayList()));
                map.put("tool", new PageInfo(new ArrayList()));
                return Response.ok(map);
            }else{
                if (group.getLevel() > 3 && StringUtils.isNotEmpty(group.getParent())) {
                    ToolGroupBean dept = dept(factory, group.getParent(), 3);
                    group.setWarehouseId(dept.getId());
                    group.setWarehouseName(dept.getName());
                }
            }
            List<ToolGroupBean> child = mapper.getChild(query);
            if (child.size() > 0) {
                // 查询组织数量
                List<Map<String, String>> childOrgCount = mapper.getChildCount(child);
                List<Map<String, String>> childToolCount = mapper.getChildToolCount(child);
                for (ToolGroupBean toolGroupBean : child) {
                    toolGroupBean.setChildNum(0);
                    toolGroupBean.setLeafNodeFlag(true);
                    for (Map<String, String> item : childOrgCount) {
                       String key = item.get("key");
                       if (key.equals(toolGroupBean.getId())) {
                           int childNum = Integer.parseInt(item.get("value"));
                           toolGroupBean.setChildNum(childNum);
                           toolGroupBean.setLeafNodeFlag(childNum == 0);
                           break;
                       }
                    }
                    for (Map<String, String> item : childToolCount) {
                        String key = item.get("key");
                        if (key.equals(toolGroupBean.getCode())) {
                            int childNum = Integer.parseInt(item.get("value"));
                            toolGroupBean.setChildNum(toolGroupBean.getChildNum() + childNum);
                            break;
                        }
                    }
                }
            }
            List<ToolGroupBean> result = new ArrayList<>();
            List<ToolGroupBean> allChildList = getAllChildList(mapper, Arrays.asList(group), result);
            // 获取所有的分类编码
            List<String> codeList = allChildList.stream().map(bean -> bean.getCode()).collect(Collectors.toList());
            List<ToolBean> toolList = new ArrayList<>();
            if (null != codeList && codeList.size() > 0) {
                query.setToolTyleCodeList(codeList);
                PageHelper.startPage(query.getPage(), query.getPageSize());
                toolList = mapper.getTools(query);
            }
            map.put("bean", group);
            map.put("group", new PageInfo(child));
            map.put("tool", new PageInfo(toolList));
            return Response.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    @Override
    @TaskAnnotation("getChildTree")
    public Response getChildTree(SessionFactory factory, String id) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
//            ToolGroupBean group = mapper.getGroup(id);
            List<ToolGroupBean> childList = mapper.getChildGroup(id);
            return Response.ok(childList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    @Override
    @TaskAnnotation("getChildGroup")
    public Response getChildGroup(SessionFactory factory, String id) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolGroupBean group = mapper.getGroup(id);
            // 获取子集组织
            List<ToolGroupBean> childList = mapper.getChildList(id);
            // 获取所有分类组织数据
            List<ToolGroupBean> list = childList.stream().filter(bean -> null != bean.getLevel() && bean.getLevel() > 3).collect(Collectors.toList());
            // 查询当前组织下的分类，即库房以下等级。包含下属子集
            List<ToolGroupBean> allChildGroup = getAllChildGroup(mapper, list);
            return Response.ok(allChildGroup);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }

    }

    /**
     * 获取库房下的所有的分类信息，包含子集，以树型返回
     *
     * @param mapper
     * @param list
     * @return
     */
    public static List<ToolGroupBean> getAllChildList(ToolAccountsManagerMapper mapper, List<ToolGroupBean> list, List<ToolGroupBean> result) {
        if (null != list && list.size() > 0) {
            result.addAll(list);
            for (ToolGroupBean toolGroupBean : list) {
                List<ToolGroupBean> childList = mapper.getChildList(toolGroupBean.getId());
                if (null != childList && childList.size() > 0) {
                    getAllChildList(mapper, childList, result);
                }
            }
        }
        return result;
    }

    /**
     * 获取库房下的所有的分类信息，包含子集，以列表返回
     *
     * @param mapper
     * @param list
     * @return
     */
    private List<ToolGroupBean> getAllChildGroup(ToolAccountsManagerMapper mapper, List<ToolGroupBean> list) {
        if (null != list && list.size() > 0) {
            for (ToolGroupBean toolGroupBean : list) {
                List<ToolGroupBean> childList = mapper.getChildList(toolGroupBean.getId());
                toolGroupBean.setChildList(childList);
                if (null != childList && childList.size() > 0) {
                    getAllChildGroup(mapper, childList);
                }
            }
        }
        return list;
    }

    @Override
    @TaskAnnotation("getWarehose")
    public Response getWarehose(SessionFactory factory, String id) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolGroupBean group = mapper.getGroup(id);
            if (null != group.getLevel() && group.getLevel() == 3) {
                return Response.ok(group);
            }
            return Response.ok(dept(factory, group.getParent(), 3));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }

    }

    @Override
    @TaskAnnotation("getDept")
    public Response getDept(SessionFactory factory, String id) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolGroupBean group = mapper.getGroup(id);
            if ("root".equals(group.getParent()) || (null != group.getLevel() && group.getLevel() <= 2)) {
                return Response.ok(group);
            }
            return Response.ok(dept(factory, group.getParent(), 2));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    @Override
    @TaskAnnotation("getAllStationGroup")
    public Response getAllStationGroup(SessionFactory factory) {
        try {
            ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
            // 获取所有场站级组织数据
            List<ToolGroupBean> allStationGroup = mapper.getAllUnitGroup();
            return Response.ok(allStationGroup);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.getMessage();
            return Response.fail();
        }
    }

    @Override
    @TaskAnnotation("getGroupQuery")
    public Response getGroupQuery(SessionFactory factory) {
        List<ToolSelect> list = new ArrayList<>();
        try {
            // TODO 获取前端查询下拉列表
            TooSelectMapper mapper = factory.getMapper(TooSelectMapper.class);
            List<Map> maps = mapper.getToolGroup("t_tool_parameter");
            if (null != maps && !maps.isEmpty()) {
                for (Map map : maps) {
                    if (!StringUtils.isEmpty(map.get("COLUMN_COMMENT").toString())) {
                        ToolSelect select = new ToolSelect();
                        select.setFieldName(map.get("COLUMN_COMMENT").toString());
                        String columnName = map.get("COLUMN_NAME").toString();
                        while (!StringUtils.isEmpty(columnName) && columnName.contains("_")) {
                            int i = columnName.indexOf("_");
                            String first = columnName.substring(0, i);
                            String secord = columnName.substring(i + 1);
                            String str = secord.substring(0, 1).toUpperCase() + secord.substring(1).toLowerCase();
                            columnName = first + str;
                        }
                        select.setFieldCode(columnName);
                        list.add(select);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.ok(list);
    }

    @Override
    @TaskAnnotation("getToolQuery")
    public Response getToolQuery(SessionFactory factory) {
        List<ToolSelect> list = new ArrayList<>();
        try {
            // TODO 获取前端查询下拉列表
            TooSelectMapper mapper = factory.getMapper(TooSelectMapper.class);
            List<Map> maps = mapper.getToolGroup("t_tool");
            if (null != maps && !maps.isEmpty()) {
                for (Map map : maps) {
                    if (!StringUtils.isEmpty(map.get("COLUMN_COMMENT").toString())) {
                        ToolSelect select = new ToolSelect();
                        select.setFieldName(map.get("COLUMN_COMMENT").toString());
                        String columnName = map.get("COLUMN_NAME").toString();
                        while (!StringUtils.isEmpty(columnName) && columnName.contains("_")) {
                            int i = columnName.indexOf("_");
                            String first = columnName.substring(0, i);
                            String secord = columnName.substring(i + 1);
                            String str = secord.substring(0, 1).toUpperCase() + secord.substring(1).toLowerCase();
                            columnName = first + str;
                        }
                        select.setFieldCode(columnName);
                        list.add(select);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.ok(list);
    }

    private ToolGroupBean dept(SessionFactory factory, String id, Integer level) {
        ToolAccountsManagerMapper mapper = factory.getMapper(ToolAccountsManagerMapper.class);
        ToolGroupBean bean = mapper.getGroup(id);
        if (null != bean.getLevel() && bean.getLevel() <= level) {
            return bean;
        } else {
            // 获取当前组织的父级
            return dept(factory, bean.getParent(), level);
        }
    }

    private Response checkToolEmpty(ToolBean bean) {
        if (StringUtils.isEmpty(bean.getName())) {
            return Response.fail("工具名称不能为空");
        }
        if (StringUtils.isEmpty(bean.getEamType())) {
            return Response.fail("工具分类不能为空");
        }
        if (StringUtils.isEmpty(bean.getPersonInCharge()) || StringUtils.isEmpty(bean.getPersonInChargeName())) {
            return Response.fail("工具负责人不能为空");
        }
        if (StringUtils.isEmpty(bean.getInventoryStatus())) {
            return Response.fail("库存状态不能为空");
        }
        if (StringUtils.isEmpty(bean.getAvailableStatus())) {
            return Response.fail("可用状态不能为空");
        }
        if (StringUtils.isEmpty(bean.getWarehouseId())) {
            return Response.fail("所属库房不能为空");
        }
        if (StringUtils.isEmpty(bean.getWarehouse())) {
            return Response.fail("所属单位不能为空");
        }
        if (StringUtils.isEmpty(bean.getToolTyleCode())) {
            return Response.fail("分区编码不能为空");
        }
        return Response.success();
    }

}
